<script setup lang="ts" name="LiveVideo">
import { useMessage } from '/@/hooks/message';
import CommonVideoPlayer, { VideoType } from '/@/libs/player/CommonVideoPlayer';
import VideoAbstract from '/@/libs/player/VideoAbstract';

const props = withDefaults(
	defineProps<{
		isInit?: boolean;
		url?: string;
		type?: VideoType;
	}>(),
	{
		url: '',
		isInit: true,
		type: VideoType.dhflv,
	}
);

defineExpose({
	init,
	unLoad,
});

onMounted(() => {
	if (props.isInit) init();
});

onUnmounted(() => {
	unLoad();
});

let videoPlayer: VideoAbstract | undefined;
let videoElement: any;
const videoLoading = ref(false);

function init() {
	if (!props.url) {
		throw new Error('url is required');
	}

	// 每次初始化先销毁
	unLoad();

	if (!CommonVideoPlayer.isSupported(props.type)) {
		throw new Error(`flv not supported`);
	}

	videoLoading.value = true;

	// 获取视频元素
	videoElement = document.getElementById('liveVideoElement');

	videoPlayer = CommonVideoPlayer.getInstance(props.type, {
		url: props.url,
		isLive: true,
		el: videoElement,
		type: 'flv',
	});

	if (!videoPlayer) return;

	// 资源解析事件监听
	videoPlayer.onLoaded(() => {
		console.log('资源解析完成');
		// 关闭loading
		videoLoading.value = false;
	});

	// 错误监听
	videoPlayer.onError(() => {
		useMessage().error('视频加载失败');
	});
}

// 卸载
function unLoad() {
	if (videoPlayer) {
		videoPlayer.destroy();
		videoPlayer = undefined;
	}
	if (videoElement) videoElement = null;
	console.log('实时监控销毁');
}
</script>

<template>
	<div class="flv-video w-full h-full flex flex-col bg-[#F3F3F3]">
		<video id="liveVideoElement" muted controls />
	</div>
</template>

<style lang="scss" scoped>
:deep(#dhHlsVideoWrappertrajectoryVideoElement),
:deep(#liveVideoElement) {
	height: 100%;
	width: 100% !important;
}

:deep(#dhHlsVdieoCloseBtntrajectoryVideoElement) {
	display: none;
}
</style>
